// Copyright 2025 CCC
//
// Licensed under the Apache License, Version 2.0 (the 'License')
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useState } from 'react';
import { Tabs } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { RouteType } from '@config/routes';
import { routers } from '@config/routes/routers';

import { login } from '@/api/login';
import { storage } from '@/utils/Storage';
import { storeGlobalUser } from '@/store/globalUser';
import logo from '@/assets/react.svg';
import { ComponTypeEnum } from '@/layout/BasicLayout';

type LoginType = 'username' | 'email' | 'phone';

const Login = () => {
  const [loginType, setLoginType] = useState<LoginType>('username');
  const navigate = useNavigate();
  const handleForgot = () => {
    navigate('/forgotPassword'); // 使用 navigate 进行路由跳转
  };
  const handleLogin = async (val: Login.LoginEntity) => {
    const { data = {} } = await login(val);
    storage.set('token', data?.access_token);
    await storeGlobalUser.getUserDetail();

    const flattenRoutes: (routers: RouteType[]) => RouteType[] = (routes: RouteType[]) => {
      const flattenedRoutes: RouteType[] = [];

      function traverse(routes: RouteType[]) {
        routes.forEach((route) => {
          flattenedRoutes.push(route);

          if (route.children) {
            traverse(route.children);
          }
        });
      }

      traverse(routes);

      return flattenedRoutes;
    };
    const resRoutes = flattenRoutes(routers);
    const findPath =
      resRoutes?.[
        resRoutes.findIndex(
          (item) =>
            item?.name ===
            storeGlobalUser?.userInfo.menus?.filter(
              (citem) => citem?.type === ComponTypeEnum.MENU,
            )?.[0].title,
        )
      ];
    console.log(findPath);
    navigate('/'); // 使用 navigate 进行路由跳转
  };
  const handleRegister = () => {
    navigate('/register'); // 使用 navigate 进行路由跳转
  };

  return (
    <div style={{ backgroundColor: 'white', height: '100vh' }}>
      <LoginForm
        logo={logo}
        title="数字门店管理平台"
        subTitle="基于NestJS +React的全栈项目"
        onFinish={async (val: Login.LoginEntity) => {
          await handleLogin(val);
        }}
      >
        <>
          {/* <Tabs centered activeKey={loginType} onChange={(activeKey: LoginType) => setLoginType(activeKey as LoginType)}>
                        <Tabs.TabPane key={'username'} tab={'账号密码登录'} />
                    </Tabs> */}
          <Tabs
            centered
            activeKey={loginType}
            onChange={(activeKey) => setLoginType(activeKey as LoginType)}
          >
            <Tabs.TabPane key={'username'} tab={'账号密码登录'} />
          </Tabs>
          {loginType === 'username' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={'prefixIcon'} />,
                }}
                placeholder="请输入用户名 admin"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={'prefixIcon'} />,
                }}
                placeholder={'请输入密码 admin'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码!',
                  },
                ]}
              />
            </>
          )}
        </>
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <a onClick={handleRegister}>立即注册</a>
          <a style={{ float: 'right' }} onClick={handleForgot}>
            忘记密码
          </a>
        </div>
      </LoginForm>
    </div>
  );
};

export default Login;
